package com.jiepos.mpos.inter.websocket.trans;

import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiepos.mpos.biz.transaction.service.LogTransJYLSService;
import com.jiepos.mpos.core.util.StringUtils;

import net.sf.json.JSONObject;

/**
 * @ClassName: TransMonitorThread
 * @Description: 交易监听线程
 * @author 孙永
 * @date 2018年1月23日 下午4:40:21
 */
public class TransMonitorThread extends Thread{
	
	private static Logger logger = LoggerFactory.getLogger(TransMonitorThread.class);
	
	private BlockingQueue<String> queue;
	
	private List<Session> list;
	
	private LogTransJYLSService logTransJYLSService;
	
	public TransMonitorThread(List<Session> list, LogTransJYLSService logTransJYLSService, BlockingQueue<String> queue){
		this.list = list;
		this.logTransJYLSService = logTransJYLSService;
		this.queue = queue;
	}
	
	@Override
	public void run(){
		while(true){
			try{
				Thread.sleep(1);
				if(!queue.isEmpty()){
					String locTransNo = queue.poll();
					if(StringUtils.isBlank(locTransNo)){
						continue;
					}
					Map<String, Object> data = logTransJYLSService.getTransByLocTransNo(locTransNo);
					if(data == null || data.isEmpty()){
						logger.info("监控交易本地流水号：{}未查询到流水数据", locTransNo);
						continue;
					}
					for(Session session : list){
						if(session.isOpen()){
							session.getAsyncRemote().sendText(JSONObject.fromObject(data).toString());
						}
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
